module Distribution.Time
        ( addDay
        , getWeekDay
        , isWorkDay
        , getWorkWeek
        , getWorkDays
        , getNextWorkDay
        )
        where

import Data.Time
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate

addDay :: Integer->LocalTime->LocalTime
addDay x (LocalTime d t) = LocalTime (addDays x d) t

getNextWorkDay :: LocalTime->LocalTime
getNextWorkDay t
        | isWorkDay (addDay 1 t)        = addDay 1 t
        | otherwise                     = getNextWorkDay (addDay 1 t)

getWeekDay :: LocalTime->Int
getWeekDay (LocalTime d _) = wd
        where (_, _, wd) = toWeekDate d

isWorkDay :: LocalTime -> Bool
isWorkDay d = (getWeekDay d) < 6

getWorkDays fd td = filter isWorkDay daysInBetween
        where   daysInBetween   = reverse $ daysBuilder startDay []
                daysBuilder x xs| x<=endDay = daysBuilder (addDay 1 x) (x:xs)
                                | otherwise = xs
                startDay        = LocalTime (localDay fd) (TimeOfDay 0 0 0)
                endDay          = LocalTime (localDay td) (TimeOfDay 0 0 0)

getWorkWeek :: Integer->Int->(LocalTime, LocalTime)
getWorkWeek year week = (startTime, endTime)
        where   startTime       = LocalTime startDay (TimeOfDay 0 0 0)
                endTime         = LocalTime endDay   (TimeOfDay 0 0 0)
                startDay        = fromWeekDate year week 1
                endDay          = fromWeekDate year week 6
